package lvbu.wang.lvbuoperator.ui.paramset.presenter;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qing.library.utils.DateUtils;
import com.qing.library.utils.L;
import com.qing.library.utils.NetWorkUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

import lvbu.wang.lvbuoperator.R;
import lvbu.wang.lvbuoperator.bean.JsonMotor;
import lvbu.wang.lvbuoperator.bean.MotorInfo;
import lvbu.wang.lvbuoperator.bean.SendCommandResult;
import lvbu.wang.lvbuoperator.common.MotorHelper;
import lvbu.wang.lvbuoperator.constants.RouteConstant;
import lvbu.wang.lvbuoperator.core.App;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.http.IotHttpHelp;
import lvbu.wang.lvbuoperator.manager.ThreadPool;
import lvbu.wang.lvbuoperator.services.BluetoothLEService;
import lvbu.wang.lvbuoperator.ui.paramset.ui.IIotParamSetView;
import lvbu.wang.lvbuoperator.widget.CustDialog;

/**
 * Created by DaiQing.Zha on 2017/2/22 0022.
 */
public class IotParamSetPresenterCompl implements IIotParamSetPresenter {

    private IIotParamSetView iIotParamSetView;
    private boolean mNeedGetFirmwareUpgrade = false;// 是否需要获取固件升级记录，当固件开始升级时，需要定时获取固件升级记录
    private long mCurrentUpgradeTime;             //当前的升级时间
    private final long SEND_UPDATE_COMMAND_DELAYED = 30 * 1000; //发送升级固件命令的时间延时时长，设为30s
    private final long UPGRADE_OVER_TIME = 2 * 60 * 1000; //如果在 2 分钟之内 固件升级的时间（firmwareUpgrade.getUpgradeDate()）还是小于 APP给固件发送升级请求的时间（发送B5时候的时间），则认为升级失败，停止升级

    public IotParamSetPresenterCompl(IIotParamSetView iIotParamSetView) {
        this.iIotParamSetView = iIotParamSetView;
    }

    @Override
    public void getMotorStatusName(final Context context, final String statusCode) {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                final String statusName = MotorHelper.getMotorStatusName(statusCode, context);
                iIotParamSetView.refreshUI_motorStatus(statusName);
            }
        });
    }

    @Override
    public void getMotorInfoByMotorId(final Context context, final String motorId) {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> queryStrings = new HashMap<String, Object>();
                queryStrings.put("motorId", motorId);
                final String source = IotHttpHelp.getData(RouteConstant.GET_MOTOR_INFO_BY_MOTOR_ID, queryStrings, true, context);
                if (IotHttpHelp.checkSource(source)) {
                    MotorInfo motorInfo = new Gson().fromJson(source, MotorInfo.class);
                    iIotParamSetView.refreshUI_motorInfo(motorInfo);
                }
            }
        });
    }

    @Override
    public void getBarcode(final Context context, final String motorId) {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> queryStrings = new HashMap<String, Object>();
                queryStrings.put("motorId", motorId);
                final String source = IotHttpHelp.getData(RouteConstant.Get_JsonMotor_Barcode_selectByMotorId, queryStrings, true, context);
                if (!IotHttpHelp.checkSource(source)) {
                    iIotParamSetView.showToast(IotHttpHelp.source2Message(context, source));
                    return;
                }
                iIotParamSetView.refreshUI_barcode(source);
            }
        });
    }

    @Override
    public void checkNewFirmwareVersion(final Context context, final long motorId) {

        Executors.newCachedThreadPool().execute(new Runnable() {// 新线程，用于向服务器提交
            @Override
            public void run() {

                Map<String, Object> queryStrings = new HashMap<String, Object>();
                queryStrings.put("motorId", motorId);
                queryStrings.put("managerId", BaseActivity.getManagerId(context));
                String source = IotHttpHelp.getData(RouteConstant.Get_JsonMotor_FirmwareInfo_New_byMotorId, queryStrings, true, context);
                if (!IotHttpHelp.checkSource(source)) {
                    return;
                }
                JsonMotor.FirmwareInfo newFirmwareInfo = new Gson().fromJson(source, JsonMotor.FirmwareInfo.class);
                if (newFirmwareInfo.getLen() > 0) { // 有新的版本
                    iIotParamSetView.refreshUI_firmwareBtnStatus(true);
                }
            }
        });
    }

    @Override
    public void clickUnbind(final Context context, final long motorId) {
        if (BaseActivity.getMotorDefault_bluetooth_connect_state(context) != BluetoothLEService.Bluetooth_CONNECTED && !NetWorkUtil.isNetworkAvailable((Activity) context)) {
            iIotParamSetView.showToast("请确保蓝牙已经连接或者手机已联网");
            return;
        }
        final View view = LayoutInflater.from(context).inflate(R.layout.view_check, null);
        CustDialog.Builder builder = new CustDialog.Builder(context, view);
        final EditText et_phone = (EditText) view.findViewById(R.id.et_phone);
        builder.setOKDialogButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, int which) {

                final String phone = et_phone.getText().toString();
                if (et_phone.length() == 0) {
                    iIotParamSetView.showToast(context.getString(R.string.toast_login_phoneCanNotNull));
                    return;
                }
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {
                        Map<String, Object> queryStrings = new HashMap<String, Object>();
                        queryStrings.put("motorId", motorId);
                        queryStrings.put("phone", phone);
                        String source = IotHttpHelp.getData(RouteConstant.GET_MOTOR_INFO_UNBIND_CHECK, queryStrings, true, context);
                        source = source.replace("\"", "");
                        if ("success".equals(source)) {
                            dialog.dismiss();
                            ((Activity) context).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    resetParam(context, phone, motorId);
                                }
                            });
                        } else {
                            iIotParamSetView.showToast("不允许解绑---" + source);
                            dialog.dismiss();
                        }
                    }
                });
            }
        });
        Dialog dialog = builder.create();
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(et_phone, InputMethodManager.SHOW_IMPLICIT);
            }
        });
        dialog.show();
    }

    @Override
    public void clickGetDataByBluetooth() {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                String sendCode = "B0";
                String sendContent = sendCode + "F" + App.getInstance().getMotorInfo().getImei() + "";
                SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, sendContent);
                if (scr.isResult()) {
                    answerProcess(scr.getAnswerContent());
                } else {
                    iIotParamSetView.showToast(IIotParamSetView.TOAST_COMM_GET_DATA_ERROR);
                }
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void clickConnectBluetooth(Context context) {
        int bluetoothStatus = BaseActivity.getMotorDefault_bluetooth_connect_state(context);
        if (!App.getInstance().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            iIotParamSetView.showToast(iIotParamSetView.TOAST_COMM_BLE_NOT_SUPPORT);
            return;
        }
        BluetoothManager mBluetoothManager = (BluetoothManager) App.getInstance().getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            iIotParamSetView.showToast(iIotParamSetView.TOAST_COMM_BLUETOOTH_NOT_OPEN);
        }
        if (bluetoothStatus == BluetoothLEService.Bluetooth_CONNECTING || bluetoothStatus == BluetoothLEService.Bluetooth_SCAN) { // 正在连接，提醒
            iIotParamSetView.showToast(iIotParamSetView.TOAST_COMM_BLE_CONNECTING);
            return;
        }
        if (bluetoothStatus == BluetoothLEService.Bluetooth_CONNECTED) { // 已连接，断开连接
            BluetoothLEService.disConnect();  // 断开车辆蓝牙
            return;
        }
        if (bluetoothStatus == BluetoothLEService.Bluetooth_UNCONNECT) { // 未连接，开始连接
            BluetoothLEService.connect(); // 连接车辆蓝牙
        }
    }

    @Override
    public void clickUpdateFirmware(final Context context, final long motorId, final String imei) {
        iIotParamSetView.refreshUI_firmwareBtnStatus(false);
        mCurrentUpgradeTime = System.currentTimeMillis() - SEND_UPDATE_COMMAND_DELAYED;

        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                String sendCode = "B5";
                String sendContent = sendCode + "F" + imei + "";
                String sendCommandResult = MotorHelper.sendCommand_http(motorId, sendCode, sendContent, context);
                Log.e("mainFirmwareUpdate", "sendCommandResult = " + sendCommandResult);
                if ("".equals(sendCommandResult)) {
                    openUpgradeProgress();
                } else {
                    iIotParamSetView.showToast(IIotParamSetView.TOAST_PARAM_SET_FIRMWARE_UPGRADE_FAIL, " - " + sendCommandResult);
                    iIotParamSetView.refreshUI_firmwareBtnStatus(true);
                }

            }
        });
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void clickBleSignalStrength(Context context) {
        if (BaseActivity.getMotorDefault_bluetooth_connect_state(context) != BluetoothLEService.Bluetooth_CONNECTED) {
            iIotParamSetView.showToast(IIotParamSetView.TOAST_COMM_BLE_IS_NOT_CONNECT);
        } else {

            try {
                BluetoothLEService.getmBluetoothGatt().readRemoteRssi();
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void clickGSMSignalStrength(final Context context, final long motorId) {
        iIotParamSetView.refreshUI_BleSignalStrength("");
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                String sendCode = "B6";
                String sendContent = sendCode + "F" + App.getInstance().getMotorInfo().getImei() + "";
                if (BaseActivity.getMotorDefault_bluetooth_connect_state(context) == BluetoothLEService.Bluetooth_CONNECTED) {
                    SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, sendContent);
                    if (scr.isResult()) {
                        answerProcess(scr.getAnswerContent());
                    } else {
                        answerError(sendCode, scr.getErrorMessage());
                    }
                } else {
                    String sendCommandResult = MotorHelper.sendCommand_http_(motorId, sendCode, sendContent, context);
                    Log.e("mainHHHH", "sendCommandResult = " + sendCommandResult);
                    answerProcess(sendCommandResult);
                }
            }
        });
    }

    @Override
    public void clickGetVoltage(final Context context, final long motorId) {
        iIotParamSetView.refreshUI_voltageStrength("");
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                String sendCode = "C0";
                String sendContent = sendCode + "F" + App.getInstance().getMotorInfo().getImei() + "";
                if (BaseActivity.getMotorDefault_bluetooth_connect_state(context) == BluetoothLEService.Bluetooth_CONNECTED) {
                    SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, sendContent);
                    if (scr.isResult()) {
                        answerProcess(scr.getAnswerContent());
                    } else {
                        answerError(sendCode, scr.getErrorMessage());
                    }
                } else {
                    String sendCommandResult = MotorHelper.sendCommand_http_(motorId, sendCode, sendContent, context);
                    answerProcess(sendCommandResult);
                }
            }
        });
    }

    @Override
    public void clickAdjustGyroAngle(final Context context, final long motorId) {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                String sendCode = "BE";
                String sendContent = sendCode + "F" + App.getInstance().getMotorInfo().getImei() + "";
                if (BaseActivity.getMotorDefault_bluetooth_connect_state(context) == BluetoothLEService.Bluetooth_CONNECTED) {
                    SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, sendContent);
                    if (scr.isResult()) {
                        answerProcess(scr.getAnswerContent());
                    } else {
                        answerError(sendCode, scr.getErrorMessage());
                    }
                } else {
                    String sendCommandResult = MotorHelper.sendCommand_http_(motorId, sendCode, sendContent, context);
                    answerProcess(sendCommandResult);
                }
            }
        });
    }

    @Override
    public void clickRestart(Context context) {
        if (BluetoothLEService.Bluetooth_CONNECTED == BaseActivity.getMotorDefault_bluetooth_connect_state(context)) {
            byte[] bytes = new byte[]{0x33};
            if (BluetoothLEService.sendSwitchByBluetooth(bytes)) {
                iIotParamSetView.showToast(IIotParamSetView.TOAST_PARAM_SET_RESET_SUCCESS);
            } else {
                iIotParamSetView.showToast(IIotParamSetView.TOAST_PARAM_SET_RESET_FAIL);
            }
        } else {
            iIotParamSetView.showToast(IIotParamSetView.TOAST_COMM_BLE_IS_NOT_CONNECT);
        }
    }

    @Override
    public void clickSelectTypeName(final Context context, final long motorId, final String imie, final String productId) {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {

                Map<String, Object> queryStrings = new HashMap<String, Object>();
                queryStrings.put("productId", productId);
                final String source = IotHttpHelp.getData(RouteConstant.Get_List_JsonMotor_MotorTypeDict_byProductId, queryStrings, true, context);
                if (!IotHttpHelp.checkSource(source)) {
                    iIotParamSetView.showToast(IotHttpHelp.source2Message(context, source));
                    return;
                }
                ((Activity) context).runOnUiThread(new Runnable() {
                    public void run() {
                        final ArrayList<String> names = new ArrayList<String>();
                        final ArrayList<String> values = new ArrayList<String>();
                        final ArrayList<String> typeCodes = new ArrayList<String>();// 用于给电机发送车辆型号
                        List<JsonMotor.MotorTypeDict> list = new Gson().fromJson(source, new TypeToken<List<JsonMotor.MotorTypeDict>>() {
                        }.getType());
                        for (int i = 0; i < list.size(); i++) {
                            JsonMotor.MotorTypeDict item = list.get(i);
                            names.add(item.getTypeName() + " (" + item.getBatteryQuantity() + "节" + item.getmAhOne() + "电池)");
                            values.add(item.getTypeName());
                            typeCodes.add(item.getTypeCode());
                        }
                        int index = -1;
                        new AlertDialog.Builder(context).setTitle("设置轮毂型号").setSingleChoiceItems(names.toArray(new String[names.size()]), index, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                iIotParamSetView.showProcess(IIotParamSetView.PROGRESS_TYPE_NAME);
                                final String selected = values.get(which);// 当前选择的
                                final String typeCode_selected = typeCodes.get(which);
                                Executors.newCachedThreadPool().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        String sendCode = "B3";
                                        String sendContent = sendCode + "F" + imie + typeCode_selected;
                                        String sendCommandResult = MotorHelper.sendCommand_http(motorId, sendCode, sendContent, context);
                                        iIotParamSetView.hideProcess();
                                        if (sendCommandResult.equals("")) {
                                            iIotParamSetView.refreshUI_typeName(selected);
                                        } else {
                                            iIotParamSetView.showToast(sendCommandResult);
                                        }
                                    }
                                });
                                dialog.cancel();
                            }
                        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        }).show();
                    }
                });
            }
        });
    }

    @Override
    public void clickSelectCircumference(final Context context, final long motorId, final String imie) {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {

                Map<String, Object> queryStrings = new HashMap<String, Object>();
                final String source = IotHttpHelp.getData(RouteConstant.Get_List_JsonSaleProduct_ProductTyreSizeDict, queryStrings, true, context);
                Log.e("mainVBN", "source1 = " + source);
                if (!IotHttpHelp.checkSource(source)) {
                    iIotParamSetView.showToast(IotHttpHelp.source2Message(context, source));
                    return;
                }
                ((Activity) context).runOnUiThread(new Runnable() {
                    public void run() {
                        final ArrayList<String> names = new ArrayList<String>();
                        final ArrayList<Float> values = new ArrayList<Float>();
                        List<JsonMotor.MotorTyreDict> list = new Gson().fromJson(source, new TypeToken<List<JsonMotor.MotorTyreDict>>() {
                        }.getType());
                        for (int i = 0; i < list.size(); i++) {
                            JsonMotor.MotorTyreDict item = list.get(i);
                            names.add("(" + item.getName() + ") " + item.getCircumference());
                            values.add(item.getCircumference());
                        }
                        int index = -1;
                        new AlertDialog.Builder(context).setTitle("设置轮胎周长").setSingleChoiceItems(names.toArray(new String[names.size()]), index, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                final float selected = values.get(which);// 当前选择的
                                iIotParamSetView.showProcess(IIotParamSetView.PROGRESS_CIRCUMFERENCE);
                                Executors.newCachedThreadPool().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        String sendCode = "AB";
                                        DecimalFormat decimalFormat = new DecimalFormat("0000");
                                        String sendContent = sendCode + "F" + imie + decimalFormat.format(selected * 1000);
                                        String sendCommandResult = MotorHelper.sendCommand_http(motorId, sendCode, sendContent, context);
                                        iIotParamSetView.hideProcess();
                                        if (sendCommandResult.equals("")) {
                                            iIotParamSetView.refreshUI_circumference(String.valueOf(selected));
                                        } else {
                                            iIotParamSetView.showToast(sendCommandResult);
                                        }
                                    }
                                });
                                dialog.cancel();
                            }

                        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        }).show();
                    }
                });
            }
        });
    }

    @Override
    public void clickAdjustPowerLevel(final Context context, final long motorId, final String imie, final int powerLevel) {
        String[] items = context.getResources().getStringArray(R.array.powerLevel);
        final int[] values = new int[100];
        for (int i = 0; i < 100; i++) {
            values[i] = i;
        }
        int index = -1;
        for (int i = 0; i < values.length; i++) {
            if (powerLevel == values[i]) {
                index = i;
                break;
            }
        }
        new AlertDialog.Builder(context).setTitle("修改助力等级").setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                iIotParamSetView.showProcess(IIotParamSetView.PROGRESS_ADJUST_POWER_LEVEL_ING);
                final int selected = values[which];// 当前选择的
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {
                        // 更新电机
                        String sendCode = "A5";
                        String selectedString = String.format("%2d", selected).replace(" ", "0");
                        String sendContent = sendCode + "F" + imie + selectedString;
                        String sendCommandResult = MotorHelper.sendCommand_http(motorId, sendCode, sendContent, context);
                        iIotParamSetView.hideProcess();
                        if (sendCommandResult.equals("")) {
                            iIotParamSetView.refreshUI_powerLevel(String.valueOf(selected));
                        } else {
                            iIotParamSetView.showToast(sendCommandResult);
                        }
                    }
                });
                dialog.cancel();
            }

        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    @Override
    public void clickAutoLockTimeSpan(final Context context, final long motorId, final String imie, int autoLockTimeSpan) {
        final String[] items = context.getResources().getStringArray(R.array.autoLockTimeSpan);
        final int[] values = new int[11];
        values[0] = 0;
        for (int i = 1; i < 11; i++) {
            values[i] = i;
        }
        int index = -1;
        for (int i = 0; i < values.length; i++) {
            if (autoLockTimeSpan == values[i]) {
                index = i;
                break;
            }
        }
        new AlertDialog.Builder(context).setTitle("修改自动锁定时间").setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                iIotParamSetView.showProcess(IIotParamSetView.PROGRESS_ADJUST_AUTO_LOCK_TIME_SPAN);
                final int selected = values[which];// 当前选择的
                ThreadPool.getInstance().addTask(new Runnable() {

                    @Override
                    public void run() {
                        // 更新电机
                        String sendCode = "A2";
                        String selectedString = String.format("%2d", selected).replace(" ", "0");
                        String sendContent = sendCode + "F" + imie + selectedString;
                        String sendCommandResult = MotorHelper.sendCommand_http(motorId, sendCode, sendContent, context);
                        iIotParamSetView.hideProcess();
                        if (sendCommandResult.equals("")) {
                            iIotParamSetView.refreshUI_autoLockTimeSpan(String.valueOf(selected));
                        } else {
                            iIotParamSetView.showToast(sendCommandResult);
                        }
                    }
                });
                dialog.cancel();
            }
        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    @Override
    public void clickLockStatus(final Context context, final long motorId, final String imie, boolean lockStatus) {
        final String[] items = {"锁定", "解锁"};
        final boolean[] values = {true, false};
        int index = -1;
        for (int i = 0; i < values.length; i++) {
            if (lockStatus == values[i]) {
                index = i;
                break;
            }
        }
        new AlertDialog.Builder(context).setTitle("锁定或解锁").setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                iIotParamSetView.showProcess(IIotParamSetView.PROGRESS_ADJUST_LOCK_STATUS);
                final boolean selected = values[which];// 当前选择的
                ThreadPool.getInstance().addTask(new Runnable() {

                    @Override
                    public void run() {
                        // 更新电机
                        String sendCode;
                        if (selected) {
                            sendCode = "A0";
                        } else {
                            sendCode = "A1";
                        }
                        String sendContent = sendCode + "F" + imie;
                        String sendCommandResult = MotorHelper.sendCommand_http(motorId, sendCode, sendContent, context);
                        iIotParamSetView.hideProcess();
                        if (sendCommandResult.equals("")) {
                            iIotParamSetView.refreshUI_lockStatus(String.valueOf(selected));
                        } else {
                            iIotParamSetView.showToast(sendCommandResult);
                        }
                    }
                });

                dialog.cancel();
            }

        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    @Override
    public void clickSpeedLimitValue(final Context context, final long motorId, final String imie, int speedValue) {
        final String[] items = context.getResources().getStringArray(R.array.speedLimit);
        final int[] values = new int[42];
        values[0] = 0;
        for (int i = 1; i < 42; i++) {
            values[i] = i + 9;
        }
        int index = -1;
        for (int i = 0; i < values.length; i++) {
            if (speedValue == values[i]) {
                index = i;
                break;
            }
        }
        new AlertDialog.Builder(context).setTitle("修改超速报警值").setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                iIotParamSetView.showProcess(IIotParamSetView.PROGRESS_ADJUST_SPEED_LIMIT_VALUE);
                final int selected = values[which];// 当前选择的
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {
                        // 更新电机
                        String sendCode = "A6";
                        String selectedString = String.format("%2d", selected).replace(" ", "0");
                        String sendContent = sendCode + "F" + imie + selectedString;
                        String sendCommandResult = MotorHelper.sendCommand_http(motorId, sendCode, sendContent, context);
                        iIotParamSetView.hideProcess();
                        if (sendCommandResult.equals("")) {
                            iIotParamSetView.refreshUI_speedLimitValue(String.valueOf(selected));
                        } else {
                            iIotParamSetView.showToast(sendCommandResult);
                        }
                    }
                });
                dialog.cancel();
            }
        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    @Override
    public void clickBikeWeight(final Context context, final long motorId, final String imie, float weightValue) {

        final String[] items = context.getResources().getStringArray(R.array.bikeWeight);
        final int[] values = new int[41];
        values[0] = 0;
        for (int i = 0; i < 41; i++) {
            values[i] = i + 10;
        }
        int index = -1;
        for (int i = 0; i < values.length; i++) {
            if (weightValue == values[i]) {
                index = i;
                break;
            }
        }
        new AlertDialog.Builder(context).setTitle("修改车重").setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                iIotParamSetView.showProcess(IIotParamSetView.PROGRESS_ADJUST_BIKE_WEIGHT);
                final float selected = values[which];// 当前选择的
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {
                        // 更新电机
                        String sendCode = "AE";
                        DecimalFormat decimalFormat = new DecimalFormat("0000");
                        String sendContent = sendCode + "F" + imie + decimalFormat.format(selected * 10);
                        String sendCommandResult = MotorHelper.sendCommand_http(motorId, sendCode, sendContent, context);
                        iIotParamSetView.hideProcess();
                        if (sendCommandResult.equals("")) {
                            iIotParamSetView.refreshUI_bikeWeight(String.valueOf(selected));
                        } else {
                            iIotParamSetView.showToast(sendCommandResult);
                        }
                    }
                });
                dialog.cancel();
            }
        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    @Override
    public void clickLoadWeight(final Context context, final long motorId, final String imie, float loadValue) {
        final String[] items = context.getResources().getStringArray(R.array.loadWeight);
        final int[] values = new int[171];
        values[0] = 0;
        for (int i = 0; i < 171; i++) {
            values[i] = i + 30;
        }
        int index = -1;
        for (int i = 0; i < values.length; i++) {
            if (loadValue == values[i]) {
                index = i;
                break;
            }
        }
        new AlertDialog.Builder(context).setTitle("修改载重").setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                iIotParamSetView.showProcess(IIotParamSetView.PROGRESS_ADJUST_LOAD_WEIGHT);
                final float selected = values[which];// 当前选择的
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {
                        // 更新电机
                        String sendCode = "AF";
                        DecimalFormat decimalFormat = new DecimalFormat("0000");
                        String sendContent = sendCode + "F" + imie + decimalFormat.format(selected * 10);
                        String sendCommandResult = MotorHelper.sendCommand_http(motorId, sendCode, sendContent, context);
                        iIotParamSetView.hideProcess();
                        if (sendCommandResult.equals("")) {
                            iIotParamSetView.refreshUI_loadWeight(String.valueOf(selected));
                        } else {
                            iIotParamSetView.showToast(sendCommandResult);
                        }
                    }
                });
                dialog.cancel();
            }

        }).setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }


    @Override
    public void getFirmwareUpgrade(final Context context) {
        if (((Activity) context).isFinishing()) return;
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                if (mNeedGetFirmwareUpgrade) {   //需要固件升级
                    Map<String, Object> params = new HashMap<>();
                    params.put("motorId", App.getInstance().getMotorInfo().getMotorId());
                    String source = IotHttpHelp.getData(RouteConstant.API_GET_FIRMWARE_UPGRADE_BY_MOTOR_ID, params, true, context);
                    Log.e("mainFirmwareUpdate", "process ---------------------- source" + source);
                    if (IotHttpHelp.checkSource(source)) {
                        JsonMotor.FirmwareUpgrade firmwareUpgrade = new Gson().fromJson(source, JsonMotor.FirmwareUpgrade.class);
                        String state = firmwareUpgrade.getState();
                        final int sectionAlready = firmwareUpgrade.getSectionAlready();
                        final int maxSection = firmwareUpgrade.getMaxSection();
                        final String firmwareVersion = firmwareUpgrade.getFirmwareVersion();
                        long longUpgradeDate = DateUtils.formatStr(firmwareUpgrade.getUpgradeDate(), DateUtils.TYPE_01);
                        if (longUpgradeDate < mCurrentUpgradeTime || (firmwareUpgrade.getState() == null || "".equals(firmwareUpgrade.getState()))) {  //如果 升级时间 小于 本次发送升级请求的时间（说明是上一次的升级记录） 或者 返回的升级记录为空
                            if (System.currentTimeMillis() - mCurrentUpgradeTime > UPGRADE_OVER_TIME) {   //如果在 2 分钟之内还是 升级时间 小于 本次发送升级请求的时间，则取消升级
                                mNeedGetFirmwareUpgrade = false;
                                iIotParamSetView.showToast(iIotParamSetView.TOAST_PARAM_SET_DOWNLOAD_PATCH_FAIL);
                                iIotParamSetView.cancelFirmwareUpgrade();
                                return;
                            }
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            getFirmwareUpgrade(context);
                            return;
                        }
                        if ("F1".equals(state)) {
                            iIotParamSetView.downloadingUpgradePatchF1(sectionAlready, maxSection);
                        }
                        if ("F2".equals(state)) {    //下载升级包成功
                            iIotParamSetView.downloadSuccessUpgradePatchF2(firmwareVersion);
                            Log.e("mainFirmwareUpdate", "process ---------------------- 2");
                        }
                        if ("F3".equals(state)) {    //下载升级包失败
                            mNeedGetFirmwareUpgrade = false;
                            iIotParamSetView.showToast(iIotParamSetView.TOAST_PARAM_SET_DOWNLOAD_PATCH_FAIL);
                            iIotParamSetView.downloadFailUpgradePatchF3();
                            Log.e("mainFirmwareUpdate", "process ---------------------- 3");
                        }
                        if ("F4".equals(state)) {    //升级成功
                            mNeedGetFirmwareUpgrade = false;
                            iIotParamSetView.showToast(iIotParamSetView.TOAST_PARAM_SET_UPGRADE_SUCCESS);
                            iIotParamSetView.upgradeFirmwareSuccessF4(firmwareVersion);
                            Log.e("mainFirmwareUpdate", "process ---------------------- 4");
                        }
                        if ("F5".equals(state)) {   //安装失败
                            mNeedGetFirmwareUpgrade = false;
                            iIotParamSetView.showToast(iIotParamSetView.TOAST_PARAM_SET_INSTALL_FAIL);
                            iIotParamSetView.upgradeFirmwareFailF5();
                            Log.e("mainFirmwareUpdate", "process ---------------------- 5");
                        }
                    } else {
                        iIotParamSetView.showToast("ERROR");
                    }
                }
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                getFirmwareUpgrade(context);
            }
        });
    }

    @Override
    public void clickChangeMotorStatus(final Context context, final long motorId, final int managerId, final String statusCode) {
        String statusName = "";
        if ("02".equals(statusCode)) {
            statusName = "电机停转";
        } else if ("03".equals(statusCode)) {
            statusName = "模拟骑行";
        } else if ("05".equals(statusCode)) {
            statusName = "出库";
        } else if ("FF".equals(statusCode)) {
            statusName = "正常";
        }
        new AlertDialog.Builder(context).setTitle("提示").setMessage("您确定要切换到 \"" + statusName + "\" 状态?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                iIotParamSetView.showProcess(IIotParamSetView.PROGRESS_CHANGE_STATUS_CHANGE_ING);
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {
                        String sendCode = "C3";
                        String sendContent = sendCode + "F" + App.getInstance().getMotorInfo().getImei() + statusCode;
                        String sendCommandResult = BluetoothLEService.sendCommandByHttp(motorId, sendCode, sendContent, context);
                        Log.e("mainHHHHHHHHHHHH", "sendCommandResult = " + sendCommandResult.toString());
                        boolean result_motor = false;
                        if (sendCommandResult.equals("")) {
                            result_motor = true;
                        } else {
                            iIotParamSetView.showToast(sendCommandResult);
                            iIotParamSetView.hideProcess();
                            return;
                        }
                        if (result_motor) {
                            try {
                                String statusName = MotorHelper.getMotorStatusName(statusCode, context);
                                iIotParamSetView.refreshUI_motorStatus(statusName);
                                iIotParamSetView.showToast("切换状态成功！");
                                Log.e("mainSTATUSCHANGED", "-----------------------------------------------" + statusName);
                            } catch (ArrayIndexOutOfBoundsException e) {
                                iIotParamSetView.showToast("切换状态失败！");
                            } catch (Exception e) {
                                iIotParamSetView.showToast("切换状态失败！");
                            } finally {
                                iIotParamSetView.hideProcess();
                            }
                        }
                    }
                });
            }
        }).setNegativeButton("取消", null).show();
    }

    /**
     * 重置参数Context context,String sendCode,String sendContent,long motorId
     */
    private void resetParam(final Context context, final String phone, final long motorId) {
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                iIotParamSetView.showProcess(IIotParamSetView.PROGRESS_UNBIND);
                //=====================================================================助力模式
                final String sendCodeAssistantMode = "C4";
                final String sendContentAssistant = sendCodeAssistantMode + "F" + App.getInstance().getMotorInfo().getImei() + "01"; //获取默认电机的imei
                SendCommandResult scrAssistant = getCommandResult(context, sendCodeAssistantMode, sendContentAssistant, motorId);

                if (scrAssistant.isResult() == true) {
                    if (!"01".equals(scrAssistant.getAnswerContent().substring(18, 20))) {
                        iIotParamSetView.showToast("设置助力模式失败");
                        iIotParamSetView.hideProcess();
                        return;
                    }
                } else {
                    iIotParamSetView.showToast("设置助力模式失败");
                    iIotParamSetView.hideProcess();
                    return;
                }
                //=====================================================================助力等级
                final String sendCodePowerLevel = "A5";
                final String sendContentPowerLevel = sendCodePowerLevel + "F" + App.getInstance().getMotorInfo().getImei() + "50"; //获取默认电机的imei
                SendCommandResult scrPowerLevel = getCommandResult(context, sendCodePowerLevel, sendContentPowerLevel, motorId);

                if (scrPowerLevel.isResult() == true) {
                    if (!"01".equals(scrPowerLevel.getAnswerContent().substring(18, 20))) {
                        iIotParamSetView.showToast("设置助力等级失败");
                        iIotParamSetView.hideProcess();
                        return;
                    }
                } else {
                    iIotParamSetView.showToast("设置助力等级失败");
                    iIotParamSetView.hideProcess();
                    return;
                }
                //=====================================================================车重
                String sendCodeBikeWeight = "AE";
                DecimalFormat decimalFormat = new DecimalFormat("0000");
                String sendContentBikeWeight = sendCodeBikeWeight + "F" + App.getInstance().getMotorInfo().getImei() + decimalFormat.format(20 * 10);
                SendCommandResult scrBikeWeight = getCommandResult(context, sendCodeBikeWeight, sendContentBikeWeight, motorId);
                if (scrBikeWeight.isResult() == true) {
                    if (!"01".equals(scrBikeWeight.getAnswerContent().substring(18, 20))) {
                        iIotParamSetView.showToast("设置车重失败");
                        iIotParamSetView.hideProcess();
                        return;
                    }
                } else {
                    iIotParamSetView.showToast("设置车重失败");
                    iIotParamSetView.hideProcess();
                    return;
                }
                //=====================================================================载重
                String sendCodeLoadWeight = "AF";
                String sendContentLoadWeight = sendCodeLoadWeight + "F" + App.getInstance().getMotorInfo().getImei() + decimalFormat.format(60 * 10);
                SendCommandResult scrLoadWeight = getCommandResult(context, sendCodeLoadWeight, sendContentLoadWeight, motorId);
                if (scrLoadWeight.isResult() == true) {
                    if (!"01".equals(scrLoadWeight.getAnswerContent().substring(18, 20))) {
                        iIotParamSetView.showToast("设置载重失败");
                        iIotParamSetView.hideProcess();
                        return;
                    }
                } else {
                    iIotParamSetView.showToast("设置载重失败");
                    iIotParamSetView.hideProcess();
                    return;
                }
                //=====================================================================自动锁定时间
                String sendCodeAutoLock = "A2";
                DecimalFormat decimalFormat_ = new DecimalFormat("00");
                String sendContentAutoLock = sendCodeAutoLock + "F" + App.getInstance().getMotorInfo().getImei() + decimalFormat.format(0);
                SendCommandResult scrAutoLock = getCommandResult(context, sendCodeAutoLock, sendContentAutoLock, motorId);
                if (scrAutoLock.isResult() == true) {
                    if (!"01".equals(scrAutoLock.getAnswerContent().substring(18, 20))) {
                        iIotParamSetView.showToast("设置自动锁定时间失败");
                        iIotParamSetView.hideProcess();
                        return;
                    }
                } else {
                    iIotParamSetView.showToast("设置自动锁定时间失败");
                    iIotParamSetView.hideProcess();
                    return;
                }
                //=====================================================================锁定状态
                final String sendCodeUnLock = "A1";
                final String sendContentUnLock = sendCodeUnLock + "F" + App.getInstance().getMotorInfo().getImei() + "";
                SendCommandResult scrUnLock = getCommandResult(context, sendCodeUnLock, sendContentUnLock, motorId);
                if (scrUnLock.isResult() == true) {
                    if (!"01".equals(scrUnLock.getAnswerContent().substring(18, 20))) {
                        iIotParamSetView.showToast("设置解锁失败");
                        iIotParamSetView.hideProcess();
                        return;
                    }
                } else {
                    iIotParamSetView.showToast("设置解锁失败");
                    iIotParamSetView.hideProcess();
                    return;
                }
                //=====================================================================超速报警值
                String sendCodeLimitSpeed = "A6";
                String sendContentLimitSpeed = sendCodeLimitSpeed + "F" + App.getInstance().getMotorInfo().getImei() + decimalFormat_.format(20);
                SendCommandResult scrLimitSpeed = getCommandResult(context, sendCodeLimitSpeed, sendContentLimitSpeed, motorId);
                if (scrLimitSpeed.isResult()) {
                    if (!"01".equals(scrLimitSpeed.getAnswerContent().substring(18, 20))) {
                        iIotParamSetView.showToast("设置超速报警失败");
                        iIotParamSetView.hideProcess();
                        return;
                    }
                } else {
                    iIotParamSetView.showToast("设置超速报警失败");
                    iIotParamSetView.hideProcess();
                    return;
                }
                //=====================================================================骑行数据
                String sendCodeTripData = "B2";
                String sendContentTripData = sendCodeTripData + "F" + App.getInstance().getMotorInfo().getImei() + "0000000000000000";
                SendCommandResult scrTripData = getCommandResult(context, sendCodeTripData, sendContentTripData, motorId);
                L.e("mainVBN", "sendContentTripData = " + sendContentTripData + "scrTripData = " + scrTripData.toString());
                if (scrTripData.isResult()) {
                    if (!"01".equals(scrTripData.getAnswerContent().substring(18, 20))) {
                        iIotParamSetView.showToast("设置骑行数据失败");
                        iIotParamSetView.hideProcess();
                        return;
                    }
                } else {
                    iIotParamSetView.showToast("设置骑行数据失败");
                    iIotParamSetView.hideProcess();
                    return;
                }
                //=====================================================================电机状态
                String sendCodeStatus = "C3";

                String sendContentStatus = sendCodeStatus + "F" + App.getInstance().getMotorInfo().getImei() + "05";
                String sendCommandResultStatus = MotorHelper.sendCommand_http_(motorId, sendCodeStatus, sendContentStatus, context);
                try {
                    if (!"01".equals(sendCommandResultStatus.substring(18, 20))) {
                        iIotParamSetView.showToast("设置状态失败");
                        iIotParamSetView.hideProcess();
                        return;
                    }
                } catch (Exception e) {
                    iIotParamSetView.showToast("设置状态失败 = " + sendCommandResultStatus);
                    iIotParamSetView.hideProcess();
                    return;
                }
                Map<String, Object> queryStrings = new HashMap<String, Object>();
                queryStrings.put("motorId", motorId);
                queryStrings.put("phone", phone);
                String source = IotHttpHelp.getData(RouteConstant.SET_MOTOR_INFO_UNBIND, queryStrings, true, context);
                source = source.replace("\"", "");
                if ("success".equals(source)) {
                    iIotParamSetView.showToast("解绑成功");
                } else {
                    iIotParamSetView.showToast("---解绑失败---" + source);
                }
                iIotParamSetView.hideProcess();
            }
        });
    }

    /**
     * 向电机发送命令
     *
     * @param sendCode
     * @param sendContent
     * @return
     */
    private SendCommandResult getCommandResult(Context context, String sendCode, String sendContent, long motorId) {
        SendCommandResult sendCommandResult = new SendCommandResult();
//        if (BaseActivity.getMotorDefault_bluetooth_connect_state(context) == BluetoothLEService.Bluetooth_CONNECTED){
//            sendCommandResult = BluetoothLEService.sendCommandByBluetooth(sendCode, sendContent);
//        }else if (NetWorkUtil.isNetworkAvailable((Activity) context)){
//            String answerContent = MotorHelper.sendCommand_http_(motorId, sendCode, sendContent, context);
//            sendCommandResult.setResult(true);
//            if ("".equals(answerContent) || answerContent == null || answerContent.length() < 20){
//                answerContent = "XXXXXXXXXXXXXXXXXXXXXXX";  //避免截断字符串时越界，所以给他设置一个很长的无效值
//            }
//            sendCommandResult.setAnswerContent(answerContent);
//        }
        String answerContent = MotorHelper.sendCommand_http_(motorId, sendCode, sendContent, context);
        sendCommandResult.setResult(true);
        if ("".equals(answerContent) || answerContent == null || answerContent.length() < 20) {
            answerContent = "XXXXXXXXXXXXXXXXXXXXXXX";  //避免截断字符串时越界，所以给他设置一个很长的无效值
        }
        sendCommandResult.setAnswerContent(answerContent);
        return sendCommandResult;
    }

    /**
     * 开启固件升级进度条
     */
    private void openUpgradeProgress() { // 开启固件升级进度条
        iIotParamSetView.preUpgradeFirmware();
        mNeedGetFirmwareUpgrade = true;
    }

    /**
     * 处理电机正确返回结果
     *
     * @param answerContent
     */
    private void answerProcess(final String answerContent) {
        int answerLength = answerContent.length();
        if (answerLength < 20) {//电机最短指令为20位
            return;
        }
        if (!answerContent.substring(3, 18).equals(App.getInstance().getMotorInfo().getImei())) {// 如果收到的imei不是当前的imei
            return;
        }
        String sendCode = answerContent.substring(0, 2);// sendCode，命令识别码
        final String motorResult = answerContent.substring(18, 20);// 指令执行结果:01成功，02失败
        if ("B0".equals(sendCode)) {
            if (motorResult.equals("01")) { // 应答成功

                L.e("mainLimit", "answerContent = " + answerContent);
                String powerLevel = answerContent.substring(20, 22); // 助力等级，不足前面补0
                int powerLevel_int = Integer.parseInt(powerLevel);
                String circumference = answerContent.substring(22, 26);// XYYY为电机轮周长值，X为整数，Y为小数
                Float circumference_Float = (float) (Float.parseFloat(circumference) / 1000.0);
                String autoLockTimeSpan = answerContent.substring(26, 28);// XX为自动锁定时间值，长度两位，不足两位前面补零
                int autoLockTimeSpan_int = Integer.parseInt(autoLockTimeSpan);
                String lockStatus = answerContent.substring(28, 30);// 电机锁定状态：01为锁定，02为未锁定
                Boolean lockStatus_BoolBoolean = lockStatus.equals("01");
                String speedLimitValue = answerContent.substring(30, 32);// XX为超速报警值，长度两位，不足两位前面补零
                int speedLimitValue_int = Integer.parseInt(speedLimitValue);
                String bikeWeight = answerContent.substring(32, 36);// XXXY为车重值，X为整数，Y为小数
                Float bikeWeight_Float = (float) (Float.parseFloat(bikeWeight) / 10.0);
                String loadWeight = answerContent.substring(36, 40);// XXXY为载重值，X为整数，Y为小数
                Float loadWeight_Float = (float) (Float.parseFloat(loadWeight) / 10.0);
                String isOnline = answerContent.substring(40, 42);// 是否在线：01为在线，02为离线
                Boolean isOnline_BoolBoolean = isOnline.equals("01");
                String isOnline_String = isOnline_BoolBoolean ? "在线" : "离线";
                String[] values = {String.valueOf(powerLevel_int), String.valueOf(circumference_Float), String.valueOf(autoLockTimeSpan_int)
                        , String.valueOf(lockStatus_BoolBoolean), String.valueOf(speedLimitValue_int), String.valueOf(bikeWeight_Float)
                        , isOnline_String, String.valueOf(loadWeight_Float)};
                iIotParamSetView.refreshUI_motorInfo(values);
            } else {
                iIotParamSetView.showToast(IIotParamSetView.TOAST_COMM_MOTOR_COMMAND_ANSWER_ERROR);
            }
        }
        if (sendCode.equals("B6")) { // 获取信号强度
            if (answerLength != 22) {
                return;
            }
            if (motorResult.equals("01")) { // 电机处理成功
                int rssi = Integer.parseInt(answerContent.substring(20));
                String signalStrength = "";
                if (rssi <= 5) {
                    signalStrength = rssi + "(极差)";
                }
                if (rssi > 5 && rssi <= 10) {
                    signalStrength = rssi + "(差)";
                }
                if (rssi > 10 && rssi <= 15) {
                    signalStrength = rssi + "(中)";
                }
                if (rssi > 15 && rssi <= 20) {
                    signalStrength = rssi + "(良)";
                }
                if (rssi > 20 && rssi <= 25) {
                    signalStrength = rssi + "(好)";
                }
                if (rssi > 25) {
                    signalStrength = rssi + "(极好)";
                }
                iIotParamSetView.refreshUI_BleSignalStrength(signalStrength);
            } else { // 电机处理失败
                iIotParamSetView.showToast(IIotParamSetView.TOAST_PARAM_SET_GET_GSM_FAIL_);
                iIotParamSetView.refreshUI_BleSignalStrength("");
            }
        }
        if (sendCode.equals("C0") && motorResult.equals("01")) {    // 应答当前电压
            if (answerLength != 24) {
                return;
            }
            String values = answerContent.substring(20, 24);
            Float voltage = Float.parseFloat(values) / 10;
            iIotParamSetView.refreshUI_voltageStrength(String.valueOf(voltage));
        }
    }

    private static final String TAG = "IotParamSetPresenterCompl";

    /**
     * 获取全部的数据
     */
    @Override
    public void all() {

    }

    /**
     * 电机响应错误应答
     *
     * @param sendCode
     * @param errorMessage
     */
    private void answerError(String sendCode, final String errorMessage) {
        if (sendCode.equals("B6")) { // 修改载重
            iIotParamSetView.showToast(IIotParamSetView.TOAST_PARAM_SET_GET_GSM_FAIL);
            iIotParamSetView.refreshUI_BleSignalStrength("");
        }
        if (sendCode.equals("C0")) { // 获取电压
            iIotParamSetView.showToast(IIotParamSetView.TOAST_PARAM_SET_GET_VOLTAGE_FAIL);
            iIotParamSetView.refreshUI_voltageStrength("");
        }

    }

}
